package com.zd.utils;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;

@Slf4j
public class MqttUtil {


    /**
     * mqtt发送payload
     *
     * @param serverURL 主机地址
     * @param clientId  clientId
     * @param name      用户名
     * @param password  密码
     * @param topic     推送主题
     * @param payload   字节包
     */
    public static void SendDataByMqtt(String serverURL, String clientId, String name, String password, String topic, byte[] payload) {
        try (MqttClient client = new MqttClient(serverURL, clientId + IdUtil.nanoId())) {
            final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
            if (StrUtil.isNotEmpty(password)) {
                mqttConnectOptions.setPassword(password.toCharArray());
            }
            mqttConnectOptions.setUserName(name);
            mqttConnectOptions.setConnectionTimeout(6);
            client.connect(mqttConnectOptions);
            if (!client.isConnected()) {
                log.info(" ***** Mqtt-connect 失败 *****");
                return;
            }
            client.publish(topic, payload, 0, false);
            log.info(" ***** Mqtt-publish 成功 *****--{}", new String(payload));
            client.disconnect();
        } catch (MqttException e) {
            log.error("Mqtt发送数据异常--{}", e.getMessage());
        }
    }
}
